package com.wcl.nullmusic.ui.activity;

import android.app.AlertDialog;
import android.app.NotificationManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;
import com.wcl.nullmusic.R;
import com.wcl.nullmusic.base.BaseActivity;
import com.wcl.nullmusic.Mp3Info;
import com.wcl.nullmusic.base.BaseAppcation;
import com.wcl.nullmusic.mode.PlayMusic;
import com.wcl.nullmusic.ui.adapter.MainViewPagerAdapter;
import com.wcl.nullmusic.ui.service.NullMusicService;
import com.wcl.nullmusic.utils.BaseUtils;
import com.wcl.nullmusic.utils.DayNightMode;
import com.wcl.nullmusic.utils.ToActivityUtils;

import java.io.File;
import java.sql.Time;

import cn.jpush.android.api.JPushInterface;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import de.greenrobot.event.EventBus;

public class MainActivity extends BaseActivity implements View.OnClickListener, Toolbar.OnMenuItemClickListener, SeekBar.OnSeekBarChangeListener {

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private MainViewPagerAdapter adapter;
    private DrawerLayout drawerLayout;
    private ActionBarDrawerToggle toggle;
    private ImageView main_music_pic, main_music_stop, main_music_next;
    private TextView main_music_songName, main_music_artist, main_dayOrNight, main_playTime;
    private SeekBar main_music_seekbar;

    private Mp3Info mp3Info;
    private boolean flag = false;
    private SharedPreferences sp;
    private int seekbarProgress;
    private boolean isFirst = true;
    private boolean isFirstFlag = true;
    private PlayMusic playMusic;

    private Intent intent;
    private NullMusicService.PlayerBinder binder;
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            binder = (NullMusicService.PlayerBinder) service;
            Toast.makeText(MainActivity.this, "Service已连接", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            binder = null;
        }
    };

    @Override
    protected int getLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected void conService() {
        EventBus.getDefault().register(this);

        intent = new Intent(this, NullMusicService.class);
        startService(intent);
        bindService(intent, connection, BIND_AUTO_CREATE);
    }

    @Override
    protected void getVaule() {
        // EventBus.getDefault().post(NullMusicService.OBTAIN_MUSIC_ALLINFO);
        //  this.seekbarProgress = sp.getInt("seekbarProgress", 0);
//
//        playMode = sp.getInt("play_mode", 0);
//        musicPosition = sp.getInt("currentPosition", 0);
        seekbarProgress = sp.getInt("seekbarProgress", 0);
    }

    @Override
    protected void initView() {
        BaseAppcation.getInstance().addActivity(this);
        ShareSDK.initSDK(this);

        toolbar = (Toolbar) findViewById(R.id.main_toolbar);
        tabLayout = (TabLayout) findViewById(R.id.main_tabLayout);
        viewPager = (ViewPager) findViewById(R.id.main_viewPager);
        adapter = new MainViewPagerAdapter(getSupportFragmentManager());
        drawerLayout = findView(R.id.main_drawLayout);
        main_music_pic = (ImageView) findViewById(R.id.main_music_pic);
        main_music_songName = (TextView) findViewById(R.id.main_music_songName);
        main_music_artist = (TextView) findViewById(R.id.main_music_artist);
        main_music_seekbar = findView(R.id.main_music_seekbar);
        main_music_stop = findView(R.id.main_music_stop);
        main_music_next = findView(R.id.main_music_next);
        this.sp = BaseAppcation.sp;
        main_dayOrNight = findView(R.id.main_dayOrNight);
        main_playTime = findView(R.id.main_playTime);


    }

    @Override
    protected void initData() {
        toolbar.setTitle("NullMusic");
        toolbar.setTitleTextColor(0xffffffff);
        setSupportActionBar(toolbar);

        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager);

        toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.Open, R.string.Close);
        drawerLayout.setDrawerListener(toggle);


    }


    @Override
    protected void listener() {
        main_music_stop.setOnClickListener(this);
        main_music_next.setOnClickListener(this);
        main_music_pic.setOnClickListener(this);
        toolbar.setOnMenuItemClickListener(this);
        main_music_seekbar.setOnSeekBarChangeListener(this);
        main_dayOrNight.setOnClickListener(this);
        main_playTime.setOnClickListener(this);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        toggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        toggle.onConfigurationChanged(newConfig);
    }

    // 播放暂停和下一首的监听
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.main_music_stop:
                if (isPlaying) {
                    isPlaying = false;
                    EventBus.getDefault().post(NullMusicService.PLAYER_PAUSE);
                    main_music_stop.setImageResource(R.mipmap.bt_playpage_button_play_press);
                } else {
                    isPlaying = true;
                    if (isFirstFlag) {
                        isFirstFlag = false;
                        PlayMusic playMusic = new PlayMusic();
                        playMusic.setState(NullMusicService.PLAYER_PLAY);
                        playMusic.setPosition(-1);
                        playMusic.setFlag(false);
                        EventBus.getDefault().post(playMusic);
                    } else
                        EventBus.getDefault().post(NullMusicService.PLAYER_START);
                    main_music_stop.setImageResource(R.mipmap.bt_playpage_button_pause_press);
                }
                break;
            case R.id.main_music_next:
                EventBus.getDefault().post(NullMusicService.PLAYER_NEXT);
                main_music_stop.setImageResource(R.mipmap.bt_playpage_button_pause_press);
                break;
            case R.id.main_music_pic:
                ToActivityUtils.startToActivity(this, MusicActivity.class);
                break;
            case R.id.main_dayOrNight:
                int theme = DayNightMode.getDayNightMode(this);
                Toast.makeText(MainActivity.this, "klklkl", Toast.LENGTH_SHORT).show();
                if (theme == DayNightMode.THEME_SUN) {
                    DayNightMode.setDayNightMode(this, DayNightMode.THEME_NIGHT);
                } else {
                    DayNightMode.setDayNightMode(this, DayNightMode.THEME_SUN);
                }
                // 注意改过主题后一定要，把activity finish在重开一遍，因为更改主题只能在oncreat中进行
                this.finish();
                this.startActivity(new Intent(this, this.getClass()));
                break;
            case R.id.main_playTime:
                showPlayTimeDialao();
                break;
        }
    }

    private boolean playeTimeFlag = false;
    private long[] time = {0l};

    private void showPlayTimeDialao() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("定时关闭");
        View view = LayoutInflater.from(this).inflate(R.layout.chat_dialog_item, null);
        final Spinner chat_item_spinner = (Spinner) view.findViewById(R.id.chat_item_spinner);
        final EditText chat_item_edit = (EditText) view.findViewById(R.id.chat_item_edit);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
        adapter.add("秒");
        adapter.add("分");
        adapter.add("时");
        // 设置下拉风格
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        chat_item_spinner.setAdapter(adapter);
        builder.setView(view);

        builder.setNegativeButton("取消定时播放", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                playeTimeFlag = false;
                handler.sendEmptyMessage(500);
            }
        });
        builder.setNeutralButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                playeTimeFlag = true;

                if (!"".equals(chat_item_edit.getText().toString())) {

                    time[0] = Long.parseLong(chat_item_edit.getText().toString().trim());
                }
                String unit = chat_item_spinner.getSelectedItem().toString();
                if (unit.equals("秒")) {
                } else if (unit.equals("分")) {
                    time[0] = time[0] * 60;
                } else if (unit.equals("时")) {
                    time[0] = time[0] * 60 * 60;
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        while (playeTimeFlag) {
                            try {
                                Thread.sleep(1000);
                                handler.sendEmptyMessage(400);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }).start();

            }
        });
        builder.show();
    }

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 400:
                    time[0] = time[0] - 1;
                    if (time[0] == 0) {
                        playeTimeFlag = false;
                        if (true) {
                            isPlaying = false;
                            EventBus.getDefault().post(NullMusicService.PLAYER_PAUSE);
                            main_music_stop.setImageResource(R.mipmap.bt_playpage_button_play_press);
                        }
                        main_playTime.setText("定时播放");
                    } else if (playeTimeFlag)
                        main_playTime.setText(BaseUtils.toDurtion2((int) time[0]));
                    break;
                case 500:
                    main_playTime.setText("定时播放");
                    break;
            }
            return false;
        }
    });

    // Menu的点击事件
    @Override
    public boolean onMenuItemClick(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.setting:
                showShare();
                break;
        }
        return false;
    }

    // seekBar的监听
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        // 正在拖动时
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        // 开始拖动时
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        // 停止拖动时
        // binder.getMediaPlayer().seekTo(dest);
        playMusic = new PlayMusic();
        playMusic.setState(NullMusicService.CHANGE_MUSIC_CURRENTPOSITION);
        playMusic.setCurrentPosition(seekBar.getProgress());
        EventBus.getDefault().post(playMusic);
    }

    @Override
    protected void onResume() {
        super.onResume();
        JPushInterface.onResume(this);
        //   EventBus.getDefault().post(NullMusicService.OBTIAN_MUSIC_DURATION);
    }


    @Override
    protected void onPause() {
        super.onPause();
        JPushInterface.onPause(this);
        Log.i("haha", "onPause");
        SharedPreferences.Editor editor = sp.edit();
        editor.putInt("currentPosition", musicPosition);
        editor.putInt("seekbarProgress", currentPostion);
        editor.commit();
    }


    private int playMode;
    private int currentPostion;
    private boolean isPlaying;
    private int duration;
    private int musicPosition;

    public void onEvent(Mp3Info mp3Info) {
        Log.i("onEvent", "onEvent(Mp3Info mp3Info)");
        this.mp3Info = mp3Info;
        if (!TextUtils.isEmpty(mp3Info.getPic())) {
            if (BaseUtils.splitStr(mp3Info.getPic()))
                Picasso.with(MainActivity.this).load(mp3Info.getPic()).placeholder(R.mipmap.ic_live_voice_press)
                        .error(R.mipmap.ic_live_voice_press).into(main_music_pic);
            else
                Picasso.with(MainActivity.this).load(new File(mp3Info.getPic())).placeholder(R.mipmap.ic_live_voice_press)
                        .error(R.mipmap.ic_live_voice_press).into(main_music_pic);
        } else
            main_music_pic.setImageResource(R.mipmap.ic_live_voice_press);
        main_music_songName.setText("歌名: " + mp3Info.getTitle());
        main_music_artist.setText("歌手: " + mp3Info.getArtist());
        main_music_seekbar.setMax(mp3Info.getDuration());
        if (isFirst) {
            isFirst = false;
            main_music_seekbar.setProgress(seekbarProgress);
        }
        isFirstFlag = false;
    }

    public void onEvent(PlayMusic playMusic) {
        Log.i("onEvent", "onEvent(PlayMusic playMusic)");
        int state = playMusic.getState();
        switch (state) {
            case NullMusicService.SEND_MUSIC_CURRENTPOSITION:
                currentPostion = playMusic.getCurrentPosition();
                main_music_seekbar.setProgress(currentPostion);
                break;
            case NullMusicService.SEND_MUSIC_PLAYERMODE:
                playMode = playMusic.getCurrentPlayMode();
                break;
            case NullMusicService.SEND_MUSIC_ISPLAYING:
                isPlaying = playMusic.isCurrentIsPlaying();
                if (isPlaying)
                    main_music_stop.setImageResource(R.mipmap.bt_playpage_button_pause_press);
                else
                    main_music_stop.setImageResource(R.mipmap.bt_playpage_button_play_press);
                break;
            case NullMusicService.SEND_MUSIC_DURATION:
                duration = playMusic.getCurrentDuration();
                main_music_seekbar.setMax(duration);
                break;
            case NullMusicService.SEND_MUSIC_POSITION:
                Log.i("mm", playMusic.getMusicPosition() + " <+++");
                // currentPostion = playMusic.getCurrentPosition();
                musicPosition = playMusic.getMusicPosition();

                break;
            case NullMusicService.SEND_MUSIC_ALLINFO:
                Log.i("onEvent", "SEND_MUSIC_ALLINFO  获取全部信息");
                currentPostion = playMusic.getCurrentPosition();
                playMode = playMusic.getCurrentPlayMode();
                isPlaying = playMusic.isCurrentIsPlaying();
                duration = playMusic.getCurrentDuration();
                Log.i("op", duration + "<++++");
                main_music_seekbar.setProgress(currentPostion);
                main_music_seekbar.setMax(duration);
                break;
        }
    }

    private void showShare() {
        ShareSDK.initSDK(this);
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();
// 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
        //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle("NullMusic");
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oks.setTitleUrl("http://sharesdk.cn");
        // text是分享文本，所有平台都需要这个字段
        oks.setText("我是分享文本，啦啦啦~");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        //     oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // http://pic.33.la/201405sy/xiaoxi/32.jpg
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl("http://sharesdk.cn");
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl("http://sharesdk.cn");
// 启动分享GUI
        oks.show(this);
    }

    @Override
    protected void onDestroy() {
        ShareSDK.stopSDK(this);
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        manager.cancelAll();
        Log.i("haha", "onDestory");
        binder = null;
        unbindService(connection);
        stopService(intent);
        System.exit(0);
        EventBus.getDefault().unregister(this);
        //结束Activity&从栈中移除该Activity
        BaseAppcation.getInstance().finishActivity(this);
        super.onDestroy();
    }
}
